package org.momo.rpc.ratelimit.impl;


import org.momo.rpc.ratelimit.RateLimiter;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;


public class SlidingWindowRateLimiter implements RateLimiter {

    private final int interval;

    private final int permitPerInterval;

    private final Queue<Long> que = new ConcurrentLinkedQueue<>();


    public SlidingWindowRateLimiter(int interval, int permitPerInterval) {
        this.interval = interval;
        this.permitPerInterval = permitPerInterval;
    }

    @Override
    public synchronized boolean limit() {
        long currentTime = System.currentTimeMillis();
        // 移除过期的请求时间戳
        while (!que.isEmpty() && currentTime - que.peek() > interval) {
            que.poll();
        }
        // 检查当前窗口内的请求数量是否超过限制
        if (que.size() < permitPerInterval) {
            // 允许请求，将当前时间戳加入队列
            que.offer(currentTime);
            return true;
        }
        return false;
    }

}
